import React, { Component, Fragment } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Card, Button, Table, Modal, message } from 'antd';
import router from 'umi/router';
import { connect } from 'dva';
import _ from 'lodash';
import styles from './AssignUsers.less';
import * as apis from '@/services/SystemMgr';
import ChoiceUser from './pages/ChoiceUser';
import Eject from '@/components/Eject';
import Mpagination from '../components/Mpagination';
import { getArrayProps } from '../utils/method';

const { confirm } = Modal;

@connect(state => ({
  user: state.SystemManageUesr,
}))
export default class AssignUsers extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      total: '0',
      pageSize: '20',
      current: '1',
      pages: '0',
      userIds: [],
      visible: false,
      assignUsersColumns: [
        {
          title: '序号',
          dataIndex: 'key',
          align: 'center',
        },
        {
          title: '用户账号',
          dataIndex: 'alias',
          align: 'left',
        },
        {
          title: '用户名称',
          dataIndex: 'userName',
          align: 'left',
        },
        {
          title: '岗位名称',
          dataIndex: 'sentryName',
          align: 'left',
        },
        {
          title: '用户类型',
          dataIndex: 'userType',
          align: 'left',
        },
        {
          title: '手机',
          dataIndex: 'phone',
          align: 'left',
        },
        {
          title: '邮箱',
          dataIndex: 'email',
          align: 'left',
        },
        {
          title: '部门编码',
          dataIndex: 'departmentCode',
          align: 'left',
        },
        {
          title: '用户性别',
          dataIndex: 'userGender',
          align: 'left',
        },
        {
          title: '操作',
          align: 'center',
          render: (text, record) => <a onClick={() => this.handleRemoveUser(record.id)}>移除</a>,
        },
      ],
      assignUsersData: [],
    };
  }

  componentDidMount() {
    this.getUserRolePageListUsing();
  }

  async getUserRolePageListUsing(current = '1', pageSize = '20') {
    this.setState({ assignUsersData: [] });
    const params = {
      current,
      pageSize: `${pageSize}`,
      roleId: this.props.location.query.id,
    };
    const UserRolePage = await apis.getUserRolePageListUsingGET({ params });
    if (UserRolePage.code === 1) {
      const arr = [];
      UserRolePage.data.list.map((item, index) => {
        const obj = {
          key: UserRolePage.data.pageSize * (UserRolePage.data.current - 1) + index + 1,
          alias: item.alias,
          userName: item.usercn,
          sentryName: item.jobname,
          landName: item.alias,
          userType: item.usertype,
          phone: item.mobile,
          email: item.mail,
          departmentCode: item.departmentnumber,
          userGender: item.genderId,
          id: item.id,
        };
        arr.push(obj);
        return arr;
      });
      this.setState({
        assignUsersData: arr,
        total: UserRolePage.data.total,
        pageSize: UserRolePage.data.pageSize,
        pages: UserRolePage.data.pages,
        current: UserRolePage.data.current,
        loading: false,
      });
    }
  }

  // 确定选择的用户
  handleOkBtnClick = () => {
    const self = this;
    const { userIds } = self.state;
    const params = {
      roleId: self.props.location.query.id,
      userIds,
    };
    if (getArrayProps(userIds, 'accountNumber').length > 0) {
      confirm({
        title: '分配用户',
        okText: '确定',
        cancelText: '取消',
        content: `当前选中${
          getArrayProps(userIds, 'accountNumber').length
        }条,确定后分配选中的用户，已选的不可重复提交。`,
        onOk() {
          apis.createUserRoleUsingPOST({ params }).then(data => {
            if (data.code === 1) {
              self.setState({ visible: false, userIds: [] });
              self.getUserRolePageListUsing();
              message.success(data.message);
            }
          });
        },
      });
    } else {
      message.warning('没有选中的用户');
    }
  };

  // 移除用户
  handleRemoveUser = async id => {
    const { current } = this.state;
    const params = {
      apiVersion: 'v1',
      id,
    };
    const data = await apis.deleteUserRoleUsingDELETE({ params });
    if (data.code === 1) {
      this.getUserRolePageListUsing(current);
    }
  };

  // 接受子组件传的选中用户
  getUserIds = ids => {
    this.setState({
      userIds: ids,
    });
  };

  // 分页切换
  handlePaginationChange = (current, pageSize) => {
    this.getUserRolePageListUsing(current, pageSize);
  };

  // 修改每页参数
  onShowSizeChange = (current, pageSize) => {
    this.handlePaginationChange(current, pageSize);
  };

  showDrawer = () => {
    this.setState({
      visible: true,
    });
  };

  onClose = () => {
    const { visible } = this.state;
    this.setState({
      visible: !visible,
    });
  };

  render() {
    const { total, pageSize, current, pages } = this.state;
    return (
      <div className={styles['assign-users']}>
        <PageHeaderWrapper
          breadcrumb={null}
          title="分配用户"
          extra={
            <Fragment>
              <Button
                onClick={() => {
                  router.push({
                    pathname: '/SystemManage/limitAdministration',
                    query: {
                      activeKey: 'special_role',
                    },
                    state: {
                      current: this.props.location.query.current,
                      pageSize: this.props.location.query.pageSize,
                    },
                  });
                }}
              >
                返回
              </Button>
              <Eject
                btnType="primary"
                value="选择用户"
                title="选择用户"
                width="80%"
                visible={this.state.visible}
                showDrawer={this.showDrawer}
                onClose={this.onClose}
                modelJsx={
                  <ChoiceUser
                    getUserIds={this.getUserIds}
                    assignUsersData={this.state.assignUsersData}
                  />
                }
                handleOkBtnClick={this.handleOkBtnClick}
              />
            </Fragment>
          }
        >
          <Card>
            <div className="content">
              <div className="information">
                <p>
                  <span>角色名称: </span>
                  {unescape(this.props.location.query.name)}
                </p>
                <p>
                  <span>角色描述: </span>
                  {unescape(this.props.location.query.describe)}
                </p>
              </div>
              <div className="table">
                <Table
                  bordered
                  columns={this.state.assignUsersColumns}
                  dataSource={this.state.assignUsersData}
                  pagination={false}
                  size="middle"
                />
              </div>

              <Mpagination
                total={total}
                pageSize={pageSize}
                current={current}
                pages={pages}
                handlePaginationChange={this.handlePaginationChange}
                onShowSizeChange={(currents, pageSizes) =>
                  this.onShowSizeChange(currents, pageSizes)
                }
              />
            </div>
          </Card>
        </PageHeaderWrapper>
      </div>
    );
  }
}
